package com.ouc.yyi.user.springcloud.user.userInfo.sentinel;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: yyi
 * @date: 2022/8/24 12:35
 * @version: 1.0
 **/
@RestController
public class SentinelController {

    @GetMapping("/sentinel/{id}")
    @SentinelResource(value = "testSentinel",
            fallback = "handlerFallback",
            blockHandler = "handlerBlockHandler",exceptionsToIgnore = {NullPointerException.class})
    public Map<String, String> testSentinel(@PathVariable("id") int id) {
        Map<String, String> map = new HashMap<>();
        if (id == 0) {
            map.put("code", "error");
            map.put("info", "参数异常");
            throw new NullPointerException("参数异常");
        }
        else {
            map.put("code", "success");
            map.put("info", "请求成功");
            System.err.println("参数正常");
        }

        return map;
    }

    @GetMapping("/block")
    @SentinelResource(value = "block",
            blockHandler = "handlerBlockHandler")
    public Map<String, String> block(@RequestParam("id") int id) {
        Map<String, String> map = new HashMap<>();
            map.put("code", "success");
            map.put("info", "请求成功");
            System.err.println("参数正常");
        return map;
    }

    public Map<String, String> handlerFallback(int id, Throwable e) {
        Map<String, String> map = new HashMap<>();
        map.put("code", "error");
        map.put("info", "进行了服务处理" + id);
        System.out.println(map);
        e.printStackTrace();
        return map;
    }

    public Map<String, String> handlerBlockHandler(int id, BlockException ex) {
        Map<String, String> map = new HashMap<>();
        map.put("code", "error");
        map.put("info", "进行了服务限流处理" + id);
        System.out.println(map);
        ex.printStackTrace();
        return map;
    }

}
